<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>发布博客 - M博客</title>
        <link rel="stylesheet" href="/static/editor_md/examples/css/style.css" />
        <link rel="stylesheet" href="http://tv.speechb.com/editor_md/css/editormd.css" />
        <link rel="stylesheet" href="http://tv.speechb.com/lib/superui/content/ui/global/bootstrap/css/bootstrap.min.css">
        <link href="http://tv.speechb.com/lib/x-editable/css/bootstrap-editable.css" rel="stylesheet"/>
        <link href="http://tv.speechb.com/lib/x-editable/css/select2-bootstrap.css" rel="stylesheet"/>
        <link href="http://tv.speechb.com/lib/select2/css/select2.min.css" rel="stylesheet"/>
    </head>
    <body>
        <div id="layout" >
            <header>
                <h1 style="text-align: center">发布博客</h1>
            </header>
            <div id="test-editormd"></div>

            <div class="row" style="padding: 0 5% 0 5%">
                <div class="form-group col-md-12">
                    <label for="title">标题</label>
                    <input type="text" class="form-control" id="title" placeholder="请输入标题名称">
                </div>

                <div class="form-group col-md-12">
                    <label>文章类型</label>
                    <br/>
                    <select id="title_select"  name="parentid" class="form-control">
                        <option selected="selected" value="0">--请选择--</option>
                    </select>
                </div>

                <div class="form-group col-md-12">
                    <label >标签（逗号隔开）</label>
                    <input id="tag" type="text" class="form-control"  placeholder="请输入标题标签">

                </div>

                <div class="form-group col-md-12">
                    <label>状态选择</label>
                    <br/>
                    <select id="status_select"  name="parentid" class="form-control select2">
                        <option selected="selected" value="0">不可见</option>
                        <option value="1">可见</option>
                    </select>
                </div>


            </div>

            <button id="submitBtn" type="button"  class="btn btn-primary center-block" style="margin-top:18px"> 发表文章 </button>
        </div>
        <script src="http://tv.speechb.com/editor_md/examples/js/jquery.min.js"></script>
        <script src="http://tv.speechb.com/editor_md/editormd.js"></script>
        <script src="http://tv.speechb.com/lib/superui/content/ui/global/bootstrap/js/bootstrap.min.js"></script>
        <script src="http://tv.speechb.com/lib/x-editable/js/bootstrap-editable.min.js"></script>
        <script src="http://tv.speechb.com/blog/js/check_login_status.1.3.js"></script>
        <script src="http://tv.speechb.com/lib/select2/js/select2.full.min.js"></script>
        <script type="text/javascript">
            var testEditor;

            function initEditor(md) {

                testEditor = editormd("test-editormd", {
                    width: "90%",
                    height: 740,
                    path: 'http://tv.speechb.com/editor_md/lib/',
                    theme: "dark",
                    previewTheme: "dark",
                    editorTheme: "pastel-on-dark",
                    markdown : md,
                    codeFold: true,
                    saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
                    searchReplace: true,
                    htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启
                    emoji: true,
                    taskList: true,
                    tocm: true,         // Using [TOCM]
                    tex: true,                   // 开启科学公式TeX语言支持，默认关闭
                    flowChart: true,             // 开启流程图支持，默认关闭
                    sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
                    imageUpload: true,
                    imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                    imageUploadURL: "./php/upload.php",
                    onload: function () {

                    }
                });
            }

            $(function() {
                $("#publish_type").select2();
                function initSelect2(id, url) {
                    $(id).select2({
                        language: "zh-CN",// 指定语言为中午，国际化才能起效
                        inputMessage: "请选择",
                        pagination: {
                            more: true
                        },
                        ajax: {
                            url: url,
                            dataType: 'json',
                            delay: 250, // 延迟显示
                            data: function (params) {
                                var query = {
                                    search: params.term,
                                    page: params.page || 1,
                                    title1_id: $("#title1_select").val(),
                                    rows: 10 //每页显示多少行
                                }

                                // Query parameters will be ?search=[term]&page=[page]
                                return query;
                            },
                            // 分页
                            processResults: function (data, params) {
                                params.page = data.next_page - 1;
                                return {
                                    results: data.data,// 后台返回数据
                                    pagination: {
                                        more: (params.page) * 10 < data.total// 总数
                                    }
                                };
                            },
                            cache: false
                        },
                        escapeMarkup: function (markup) {
                            return markup;
                        },
                        minimumInputLength: 0,// 0长度及搜索所以
                        templateResult: function (repo) {// 显示的结果集格式，需要自己写CSS
                            // 正在检索
                            if (repo.loading) return repo.text;
                            var markup = repo.text;
                            var markup = "";
                            markup += "<div class ='select2-result-repository_statistics'>"
                                + "<div class='select2-result-repository_forks'><i class = 'fa fa-bolt'></i> &nbsp;" + repo.text + "</div>"
                                + "</div>";
                            return markup;
                        },
                        templateSelection: function (repo) {
                            // 选中某一列后文本框
                            return "<div>" + repo.text || repo.id + "</div>";
                        },
                        placeholder: '请选择'
                    });
                }

                function initTitle2() {
                    initSelect2("#title_select", "/menu/select");
                }

                initTitle2();
                $("#submitBtn").click(function () {
                    $("#submitBtn").attr("disabled", "disabled")
                    var title = $("#title").val();
                    var mkContent = testEditor.getMarkdown();
                    var htmlContent = testEditor.getHTML();
                    var publishType = $("#title_select").val();
                    var tag = $("#tag").val();
                    var status = $("#status_select").val();
                    var data = {
                        title: title,
                        html_content: htmlContent,
                        markdown_content: mkContent,
                        tag: tag,
                        type_id: publishType,
                        status: status
                    };
                    if (id != null) {
                        data["id"] = id;
                        updateArticle(data);
                    } else {
                        publishArticle(data);
                    }
                });

                function publishArticle(data) {
                    $.ajax({
                        type: "POST",
                        url: "/blog/publish",
                        data: data,
                        //请求成功
                        success: function (result) {
                            if (result.code == 1) {
                                toast("发布成功", 1500);
                                $('#title').val("");
                                testEditor.clear();
                            } else {
                                if (result.code == -10) {
                                    toast("请先登录！", 1500);
                                    window.open("/login");
                                } else {
                                    toast(result.message, 1500);
                                }
                            }
                            $("#submitBtn").removeAttr("disabled");
                        },
                        error: function (e) {
                            console.log(e);
                            toast("出现异常啊！", 1500);
                            $("#submitBtn").removeAttr("disabled");
                        }
                    });
                }

                function updateArticle(data) {
                    $.ajax({
                        //请求方式
                        type: "PUT",
                        //请求地址
                        url: "/blog/update",
                        //数据，json字符串
                        data: data,
                        //请求成功
                        success: function (result) {
                            if (result.code == 1) {
                                toast("发布成功", 1500);
                            } else {
                                if (result.code == -10) {
                                    toast("请先登录！", 1500);
                                    window.open("/login");
                                } else {
                                    toast(result.message, 1500);
                                }
                            }
                            $("#submitBtn").removeAttr("disabled");
                            console.log(result);
                        },
                        error: function (e) {
                            $("#submitBtn").removeAttr("disabled");
                        }
                    });
                }

                $("#publish_type").select2();

                function getQueryVariable(variable) {
                    var query = window.location.search.substring(1);
                    var vars = query.split("&");
                    for (var i = 0; i < vars.length; i++) {
                        var pair = vars[i].split("=");
                        if (pair[0] == variable) {
                            return pair[1];
                        }
                    }
                    return null;
                }

                var id = null;

                function dealUpdate() {
                    id = getQueryVariable("id");
                    if (id == null) {
                        initEditor("");
                        return;
                    }
                    $.ajax({
                        type: "GET",
                        url: "/blog/update_info",
                        data: {
                            "id": id
                        },
                        success: function (result) {
                            if (result.code == 1) {
                                $("#title").val(result.data.title);
                                $("#tag").val(result.data.tag);
                                // $("#title_select").append(new Option(result.data.name, result.data.article_type_id, true, true));//第一个参数时id,第二个参数是text
                                // $("#title_select").trigger("change");
                                initEditor(result.data.markdown_content)
                            } else {
                                initEditor("")
                                toast(result.message, 1500);
                            }
                            console.log(result);
                        },
                        error: function (e) {
                            initEditor("")
                        }
                    });
                }

                dealUpdate();
            })
        </script>
    </body>
</html>